<template>
  <view class="detail-container">
    <scroll-view scroll-y class="scroll-content" :scroll-into-view="scrollId" scroll-with-animation>
      <!-- Carousel -->
      <swiper class="swiper" circular :indicator-dots="true" :autoplay="true" interval="3000" duration="500">
        <swiper-item v-for="(item, index) in fileList" :key="index">
          <image :src="item" mode="aspectFill"></image>
        </swiper-item>
      </swiper>

      <!-- Notice Banner -->
<!--      <view class="notice-banner" v-show="noticeShow">-->
<!--        <u-icon name="volume" color="#fff" size="28rpx"></u-icon>-->
<!--        <text class="notice-text">{{ station.notice }}</text>-->
<!--        <u-icon name="close" color="#fff" size="28rpx" @click="closeNotice"></u-icon>-->
<!--      </view>-->

     <view class="detail-content" id="detail">
       <!-- Station Header -->
       <view class="station-header">
         <view class="status-name">
           <view class="status" v-if="getOpenStatus(station) === 'OPEN'">营业中</view>
           <view class="status2" v-else>歇业中</view>
           <text class="name">{{ station.plotName }}</text>
           <image class="quality-badge" src="/static/images/quality.png" mode="aspectFit"></image>
         </view>
         <view class="time-power">
           <view class="time">
             <u-icon name="clock" size="24rpx" color="#666"></u-icon>
             <text>营业时间：</text>
             <text>{{ station.openingStart }}至{{ station.openingEnd }}</text>
           </view>
           <view class="time">
             <u-icon name="phone" size="24rpx" color="#666"></u-icon>
             <text>联系电话：</text>
             <text class="value phone" @click="openPhone(station.servicePhone)">{{ station.servicePhone }}</text>
           </view>
<!--           <view class="power">-->
<!--             <u-icon name="zap" size="24rpx" color="#666"></u-icon>-->
<!--             <text>最大功率 {{ station.maxPower }}</text>-->
<!--           </view>-->
         </view>
         <!-- Facility Icons -->
         <view class="facility-icons">
           <view class="facility-item" v-for="(item, index) in facilities || []" :key="index">
             <u-icon :name="item.icon" size="40rpx" color="#666"></u-icon>
             <text style="margin-left: 10rpx">{{ item.name  || ''}}</text>
           </view>
         </view>
       </view>
       <!-- Address Bar -->
       <view class="address-bar" @click="toAddress">
          <div style="display: flex;align-items: center">
            <image class="location" src="/static/home/location.png" alt=""/>
            <text class="address">{{ station.address  || ''}}</text>
          </div>
          <div style="display: flex;align-items: center">
            <image style="margin-left: 6rpx" class="location" src="/static/home/map.png" alt=""/>
            <text class="distance">{{ station.distance || 0 }}公里</text>
          </div>
       </view>

       <!-- Charger Status -->
       <view class="charger-status">
         <view class="charger-item fast" v-if="station.fastCharger">
           <text class="type">快</text>
           <view class="count">
             <text class="highlight">空闲 {{ station.fastCharger.free || 0}}</text>
             <text class="total">| 共{{ station.fastCharger.total || 0 }}</text>
           </view>
         </view>
         <view class="charger-item slow" v-if="station.fastCharger">
           <text class="type">慢</text>
           <view class="count">
             <text class="highlight">空闲 {{ station.slowCharger.free || 0 }}</text>
             <text class="total">| 共{{ station.slowCharger.total || 0 }}</text>
           </view>
         </view>
       </view>

       <!-- Tab Navigation -->
       <view class="tab-nav">
         <view :class="['tab-item', activeId === 'detail' ? 'active' : '']" @click="activeId = 'detail'; scrollId = 'detail'">电站详情</view>
<!--         <view :class="['tab-item', activeId === 'list' ? 'active' : '']" @click="activeId = 'list'; scrollId = 'list'">终端信息</view>-->
<!--         <view :class="['tab-item', activeId === 'detail']">评价</view>-->
       </view>

       <!-- Price Info -->
       <view class="price-info b-r">
         <view class="current-price">
           <text class="number">{{ formattedPrice  || '0.00'}}</text>
           <text class="unit">元/度</text>
         </view>
         <view class="price-details">
           <view class="price-item" v-for="(item, index) in priceList" :key="index">
             <div style="display: flex;align-items: center">
               <text class="type">{{ item.type  || ''}}</text>
               <view class="time-range">{{ item.startTime || '' }}~{{ item.endTime  || ''}}</view>
             </div>
             <view class="price-breakdown">
               <text class="total-price">{{ item.totalPrice || '0.00'}}元/度</text>
               <text class="detail">（电费{{ item.electricityFee || '0.00' }}元，服务费{{ item.serviceFee || '0.00'}}元）</text>
             </view>
           </view>
         </view>
       </view>

       <!-- Station Info -->
<!--       <view class="station-info b-r">-->
<!--         <view class="info-item">-->
<!--           <text class="label">营业信息</text>-->
<!--           <text class="value">{{ station.startTime }} - {{ station.endTime }}</text>-->
<!--         </view>-->
<!--         <view class="info-item">-->
<!--           <text class="label">运营商</text>-->
<!--           <text class="value">{{ station.operator }}</text>-->
<!--         </view>-->
<!--         <view class="info-item">-->
<!--           <text class="label">停车费用</text>-->
<!--           <text class="value">{{ station.parkingFee }}</text>-->
<!--         </view>-->
<!--         <view class="info-item">-->
<!--           <text class="label">支付方式</text>-->
<!--           <text class="value">{{ station.payment }}</text>-->
<!--         </view>-->
<!--         <view class="info-item">-->
<!--           <text class="label">联系电话</text>-->
<!--           <text class="value phone" @click="openPhone(station.phone)">{{ station.phone }}</text>-->
<!--         </view>-->
<!--       </view>-->
       <ChargingPileList :stationId="stationId" :pileList="pileList"/>
     </view>
    </scroll-view>

    <!-- Bottom Action Bar -->
    <view class="bottom-actions">
      <view class="action-buttons">
<!--        <view class="action-btn">-->
<!--          <u-icon name="share" size="40rpx" color="#666"></u-icon>-->
<!--          <text>分享</text>-->
<!--        </view>-->
<!--        <view class="action-btn">-->
<!--          <u-icon name="heart" size="40rpx" color="#666"></u-icon>-->
<!--          <text>收藏</text>-->
<!--        </view>-->
<!--        <view class="action-btn">-->
<!--          <u-icon name="info-circle" size="40rpx" color="#666"></u-icon>-->
<!--          <text>报修</text>-->
<!--        </view>-->
      </view>
<!--      <button class="reserve-btn">预约</button>-->
      <button class="charge-btn" @click="handleScane">扫码充电</button>
    </view>
  </view>
</template>

<script>
import ChargingPileList from "./components/charging-pile-list.vue";
import notice from "../notice/index.vue";
export default {
  name: "station",
  components: {
    ChargingPileList
  },
  data() {
    return {
      noticeShow: false,
      activeId: 'detail',
      scrollId: '',
      station: {

      },
      facilities: [
      ],
      priceList: [

      ],
      pileList: [],
      stationId: ''
    }
  },
  computed: {
    notice() {
      return notice
    },
    formattedPrice() {
      if (!this.priceList || this.priceList.length === 0) return '0.00'

      // 获取当前时间
      const now = new Date()
      const currentHour = now.getHours()
      const currentMinute = now.getMinutes()
      const currentTimeInMinutes = currentHour * 60 + currentMinute

      // 查找当前时间所属的时间段
      const currentPeriod = this.priceList.find(period => {
        const [startHour, startMinute] = period.startTime.split(':').map(Number)
        const [endHour, endMinute] = period.endTime.split(':').map(Number)

        const startTimeInMinutes = startHour * 60 + startMinute
        const endTimeInMinutes = endHour * 60 + endMinute

        // 处理跨天的情况
        if (endTimeInMinutes < startTimeInMinutes) {
          return currentTimeInMinutes >= startTimeInMinutes || currentTimeInMinutes <= endTimeInMinutes
        }

        return currentTimeInMinutes >= startTimeInMinutes && currentTimeInMinutes <= endTimeInMinutes
      })

      return currentPeriod ? currentPeriod.totalPrice : this.priceList[0].totalPrice
    },
    fileList() {
      return (this.station.filePathAll || '').split(',')
    }
  },
  onLoad({ stationId, distance }) {
    console.log('stationId', stationId)
    this.stationId = stationId
    uni.showLoading({
      title: '加载中'
    })
    this.$api.getStationDetail({
      id: stationId
    }).then(res => {
      console.log('res',res)
      let fastCharger = null
      let slowCharger = null
      if (res.fastChargerTotal) {
        fastCharger = {
          free: res.occupiedFastCharger,
          total: res.fastChargerTotal
        }
      }
      if (res.slowChargerTotal) {
        slowCharger = {
          free: res.occupiedSlowCharger,
          total: res.slowChargerTotal
        }
      }
      this.station = {
        ...res,
        fastCharger,
        slowCharger,
        distance,
      }
    }).finally(() => {
      uni.hideLoading()
    })

    this.$api.getStationPriceList({
      plotId: stationId
    }).then(res => {
      this.priceList = res.map(item => {
        let typeMap = {
          // 0123 尖峰平谷
          0: '尖',
          1: '峰',
          2: '平',
          3: '谷'
        }
        return {
          type: typeMap[item.ruleType] || item.ruleType,
          startTime:item.startTime,
          endTime: item.endTime,
          totalPrice: (Number(item.serviceMoney || 0) + Number(item.chargingPrice || 0)).toFixed(2),
          electricityFee: item.chargingPrice,
          serviceFee: item.serviceMoney
        }
      })
    })
  },
  onShow() {
    if (this.stationId) {
      uni.showLoading()
      this.$api.getGunList({
        plotId: this.stationId
      }).then(res => {
        this.pileList = res.map(item => {
          let statues = ''
          let statusText = ''
          // 	充电状态 0 离线 1故障 2 空闲 3充电中
          switch (item.chargeState) {
            case 0:
              statues = 'offline'
              statusText = '离线'
              break
            case 1:
              statues = 'fault'
              statusText = '故障'
              break
            case 2:
              statues = 'free'
              statusText = '空闲'
              break
            case 3:
              statues = 'charging'
              statusText = '充电中'
              break
            default:
              statues = 'offline'
              statusText = '离线'
          }
          return {
            name: item.deviceName,
            code: item.portCode,
            type: item.deviceType,
            power: item.ratedOutputPower,
            voltage: item.outputCurrentRange,
            current: item.currentForm,
            standard: item.accordingGb,
            status: statues,
            statusText,
            stationId: item.stationId,
            deviceId: item.stationId,
            portId: item.portId
          }
        })
        console.log('this.pileList',this.pileList)
      }).finally(() => {
        uni.hideLoading()
      })
    }
  },
  methods: {
    getOpenStatus(res) {
      console.log(res)
      let plotStatus = ''
      if (res.openingStart && res.openingEnd) {
        const [startHour, startMinute] = res.openingStart.split(':').map(Number);
        const [endHour, endMinute] = res.openingEnd.split(':').map(Number);
        const currentHour = new Date().getHours();
        const currentMinute = new Date().getMinutes();

        if ((currentHour > startHour || (currentHour === startHour && currentMinute >= startMinute)) &&
            (currentHour < endHour || (currentHour === endHour && currentMinute <= endMinute))) {
          plotStatus = 'OPEN'
        }
      }
      console.log('plotStatus',plotStatus)
      return plotStatus
    },
    closeNotice() {
      // Handle notice close
      this.noticeShow = false
    },
    showPriceDetail() {
      // Show price detail
    },
    openPhone(phone) {
      // Open phone dialer
      uni.makePhoneCall({
        phoneNumber: phone
      })
    },
    toAddress() {
      // 去地图查看位置
      uni.openLocation({
        latitude: Number(this.station.lat),    // 纬度
        longitude: Number(this.station.lng),  // 经度
        name: this.station.plotName,           // 位置名称
        address: this.station.address,     // 详细地址
        scale: 18,                        // 地图缩放级别，范围 3-20，默认 18
        success: () => {
          console.log('打开地图成功')
        },
        fail: (err) => {
          console.log('打开地图失败：', err)
          uni.showToast({
            title: '打开地图失败',
            icon: 'none'
          })
        }
      })
    },
    handleScane() {
      // 调用扫码API
      uni.scanCode({
        onlyFromCamera: true,
        scanType: ['qrCode'],
        success: (res) => {
          console.log('扫码结果：', res)
          if (!res.path) {
            uni.showToast({
              title: '无效的二维码',
              icon: 'none'
            })
          } else {
            uni.navigateTo({
              url: '/' + res.path
            })
          }
        },
        fail: (err) => {
          console.log('扫码失败：', err)
          if (err.errMsg.includes('cancel')) {
            return
          }
          uni.showToast({
            title: '扫码失败',
            icon: 'none'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #F3F5F5;
  position: relative;
  .detail-content {
    padding: 0 24rpx;
    .b-r {
      border-radius: 24rpx;
    }
  }
}

.scroll-content {
  flex: 1;
  height: 0;
  overflow-y: auto;
  padding-bottom: 120rpx;
}

.swiper {
  width: 100%;
  height: 420rpx;
  position: relative;

  image {
    width: 100%;
    height: 100%;
  }

  .swiper-indicator {
    position: absolute;
    right: 20rpx;
    bottom: 20rpx;
    background: rgba(0, 0, 0, 0.6);
    color: #FFFFFF;
    padding: 4rpx 12rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
  }
}

.notice-banner {
  display: flex;
  align-items: center;
  background: rgba(0, 0, 0, 0.6);
  padding: 16rpx 24rpx;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;

  .notice-text {
    flex: 1;
    color: #FFFFFF;
    font-size: 24rpx;
    margin: 0 16rpx;
  }
}

.station-header {
  background: #FFFFFF;
  padding: 24rpx;
  border-radius: 24rpx 24rpx 0 0;

  .status-name {
    display: flex;
    align-items: center;

    .status {
      background: #5494FE;
      color: #FFFFFF;
      font-size: 24rpx;
      padding: 4rpx 12rpx;
      border-radius: 8rpx;
    }
    .status2 {
      background: #acaba8;
      color: #FFFFFF;
      font-size: 24rpx;
      padding: 4rpx 12rpx;
      border-radius: 8rpx;
    }
    .name {
      font-size: 32rpx;
      font-weight: 500;
      margin: 0 12rpx;
    }

    .quality-badge {
      width: 80rpx;
      height: 32rpx;
    }
  }

  .time-power {
    margin-top: 16rpx;
    color: #666;
    font-size: 24rpx;

    .time, .power {
      display: flex;
      align-items: center;
      margin: 8rpx 0;

      text {
        margin-left: 8rpx;
      }

      .phone {
        color: #5494FE;
      }
    }
  }
}

.facility-icons {
  background: #FFFFFF;
  display: flex;
  padding: 24rpx;
  .facility-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 18rpx;
    background: rgba(84, 148, 254, .1);
    margin-right: 12rpx;
    padding: 6rpx 24rpx;
    text {
      font-size: 24rpx;
      color: #5494FE;
    }
  }
}

.address-bar {
  background: #04C8AE;
  padding: 16rpx 24rpx;
  display: flex;
  align-items: center;
  border-radius: 0 0 24rpx 24rpx;
  margin-bottom: 24rpx;
  justify-content: space-between;

  .location {
    width: 28rpx;
    height: 34rpx;
    flex-shrink: 0;
  }
  .address {
    flex: 1;
    color: #FFFFFF;
    font-size: 28rpx;
    margin: 0 16rpx;
  }

  .distance {
    color: #FFFFFF;
    font-size: 24rpx;
  }
}

.charger-status {
  display: flex;
  padding:0 24rpx;
  margin-bottom: 16rpx;
  gap: 24rpx;

  .charger-item {
    flex: 1;
    display: flex;
    align-items: center;
    padding: 20rpx;
    background: #F8F9FC;
    border-radius: 24rpx;
    &.fast {
      background: #5494FE;
      .type {
        color: #5494FE;
      }
    }
    &.slow {
      background: #FF8000;
      .type {
        color: #FF8000;
      }
    }
    .type {
      flex-shrink: 0;
      font-size: 28rpx;
      width: 60rpx;
      height: 60rpx;
      text-align: center;
      line-height: 60rpx;
      font-weight: 500;
      background-color: #ffffff;
      border-radius: 50%;
    }

    .count {
      margin-left: 20rpx;
      display: flex;
      align-items: center;
      gap: 8rpx;

      .highlight {
        font-size: 28rpx;
        color: #ffffff;
        font-weight: 500;
      }

      .total {
        font-size: 24rpx;
        color: #ffffff;
      }
    }
  }
}

.tab-nav {
  display: flex;
  padding: 0 24rpx;
  margin-bottom: 24rpx;
  .tab-item {
    padding: 24rpx 0;
    margin-right: 48rpx;
    font-size: 28rpx;
    color: #666;
    position: relative;

    &.active {
      color: #333;
      font-weight: 500;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 4rpx;
        background: #04C8AE;
      }
    }
  }
}

.price-info {
  background: #FFFFFF;
  padding: 24rpx;
  margin-bottom: 16rpx;

  .current-price {
    display: flex;
    align-items: baseline;

    .number {
      font-size: 48rpx;
      font-weight: 500;
      color: #333;
    }

    .unit {
      font-size: 24rpx;
      color: #666;
      margin-left: 8rpx;
    }
  }

  .price-note {
    font-size: 24rpx;
    color: #666;
    margin: 8rpx 0 24rpx;
  }

  .price-details {
    .price-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16rpx 0;
      border-bottom: 2rpx solid #F5F5F5;

      .type {
        font-size: 24rpx;
        color: #04C8AE;
        background: rgba(4, 200, 174, 0.1);
        padding: 4rpx 12rpx;
        border-radius: 4rpx;
        margin-right: 12rpx;
      }
      &:last-child {
        border-bottom: none;
      }

      .time-range {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }

      .price-breakdown {
        display: flex;
        align-items: center;
        gap: 8rpx;

        .total-price {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }

        .detail {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
}

.station-info {
  background: #FFFFFF;
  margin-top: 16rpx;
  padding: 24rpx;

  .info-item {
    display: flex;
    margin: 16rpx 0;

    .label {
      width: 140rpx;
      color: #666;
      font-size: 28rpx;
    }

    .value {
      flex: 1;
      color: #333;
      font-size: 28rpx;

      &.phone {
        color: #5494FE;
      }
    }
  }
}

.bottom-actions {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #FFFFFF;
  padding: 16rpx 24rpx;
  display: flex;
  align-items: center;
  border-top: 2rpx solid #F5F5F5;
  z-index: 100;
}

.action-buttons {
  display: flex;
  margin-right: 24rpx;

  .action-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-right: 48rpx;

    text {
      font-size: 24rpx;
      color: #666;
      margin-top: 8rpx;
    }
  }
}

button {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 16rpx;

  &.reserve-btn {
    background: #F5F5F5;
    color: #333;
  }

  &.charge-btn {
    background: #04C8AE;
    color: #FFFFFF;
  }
}
</style>
